package com.mljr.example.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.ctakit.sdk.util.EncoderUtils;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.mljr.example.base.Global;
import com.mljr.example.bean.PageContent;

import java.sql.SQLException;

public class DBHelper extends OrmLiteSqliteOpenHelper {

    Class<?>[] tableClasss = new Class<?>[]{PageContent.class};

    public DBHelper(Context context) {
        super(context, EncoderUtils.md5(Global.getUUID() + "") + ".data", null, DbConfig.DATABASE_VERSION);

    }

    public void onCreate(SQLiteDatabase arg0, ConnectionSource cs) {

        try {
            for (int i = 0; i < tableClasss.length; i++) {
                TableUtils.createTable(cs, tableClasss[i]);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    ;


    @Override
    public void onUpgrade(SQLiteDatabase sd, ConnectionSource cs, int oldVerssion, int version) {
        try {
            for (Class<?> cls : tableClasss) {
                TableUtils.dropTable(cs, cls, true);
            }
            onCreate(sd, cs);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void clear() {
        try {
            for (Class<?> cls : tableClasss) {
                TableUtils.dropTable(this.getConnectionSource(), cls, true);
            }
            onCreate(this.getWritableDatabase(), this.getConnectionSource());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void close() {
        super.close();
    }

}
